package com.sto.stoapp.db.manager;

import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.sto.stoapp.db.StoDataBase;
import com.sto.stoapp.db.constant.ScanRuleConstant;
import com.sto.stoapp.db.constant.StoBaseConstant;
import com.sto.stoapp.http.response.download.info.ScanRuleInfo;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.util.UnifiedStaticType;

/**
 * 条码类型管理类
 * 
 * @author cjb
 * 
 */
public class ScanRuleDBManager extends StoDataBase implements
		DownLoadDao<ScanRuleInfo> {
	static ScanRuleDBManager mgr;
	private static final String REGULAR_BY_TYPE_SQL = "select "
			+ ScanRuleConstant.PREFIX + "," + ScanRuleConstant.SCANLENGTH
			+ " from " + SCAN_RULE_TABLE + " where " + ScanRuleConstant.KEY
			+ "=?";
	private static final String SPECIFIC_REGULAR_SQL = "select "
			+ ScanRuleConstant.PREFIX + "," + ScanRuleConstant.SCANLENGTH
			+ " from " + SCAN_RULE_TABLE + " where "
			+ ScanRuleConstant.BARCODECHECK + "=?";

	private ScanRuleDBManager(Context context) {
		super(context);

	}

	public static ScanRuleDBManager getInstance(Context c) {
		if (mgr == null)
			mgr = new ScanRuleDBManager(c);
		return mgr;
	}

	public boolean insert(ScanRuleInfo entity) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long res = -1;
			try {
				ContentValues values = new ContentValues();
				values.put(ScanRuleConstant.KEY, entity.key);
				values.put(ScanRuleConstant.VALUE, entity.value);
				values.put(ScanRuleConstant.TYPE, entity.type);
				values.put(ScanRuleConstant.BACKUP1, entity.backup1);
				values.put(ScanRuleConstant.VERSION, entity.version);
				values.put(ScanRuleConstant.PREFIX, entity.prefix);
				values.put(ScanRuleConstant.SUFFIX, entity.suffix);
				values.put(ScanRuleConstant.BARCODECHECK, entity.barcodeCheck);
				values.put(ScanRuleConstant.SCANLENGTH, entity.scanLength);
				values.put(ScanRuleConstant.ID, entity.id);
				values.put(STATUS, entity.status);
				res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
						.insert(ScanRuleConstant.SCAN_RULE_TABLE, null, values);
				if (res > 0) {
					Log.d("插入一条 条码类型信息", "成功");
				} else {
					Log.d("插入一条 条码类型信息", "失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("insert", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
			return res > 0 ? true : false;
		}
	}

	@Override
	public String getMaxVersion() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			String version = "0";
			Cursor c = null;
			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.READ_DATABASE);
				c = db.rawQuery(getMaxVersionSql(SCAN_RULE_TABLE), null);
				if (c != null && c.moveToNext()) {
					version = c.getString(c
							.getColumnIndex(StoBaseConstant.VERSION));
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeCursor(c);
				closeDb(UnifiedStaticType.READ_DATABASE);
			}
			return version;
		}
	}

	@Override
	public boolean replace(ContentValues values) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long result = 0;
			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
				result = db.replace(SCAN_RULE_TABLE, null, values);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result > 0;
		}
	}

	@Override
	public void deleteDataByStatus(String status) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {

			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
				db.delete(SCAN_RULE_TABLE, STATUS + "=?",
						new String[] { status });
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}

		}
	}

	@Override
	public ContentValues buildContentValues(ScanRuleInfo entity) {
		ContentValues values = new ContentValues();
		values.put(ScanRuleConstant.KEY, entity.key);
		values.put(ScanRuleConstant.VALUE, entity.value);
		values.put(ScanRuleConstant.TYPE, entity.type);
		values.put(ScanRuleConstant.BACKUP1, entity.backup1);
		values.put(ScanRuleConstant.VERSION, entity.version);
		values.put(ScanRuleConstant.PREFIX, entity.prefix);
		values.put(ScanRuleConstant.SUFFIX, entity.suffix);
		values.put(ScanRuleConstant.BARCODECHECK, entity.barcodeCheck);

		values.put(ScanRuleConstant.SCANLENGTH, entity.scanLength);
		values.put(ScanRuleConstant.ID, entity.id);
		values.put(STATUS, entity.status);
		return values;
	}

	/**
	 * 插入多数据
	 * 
	 * @param entity
	 * @return
	 */
	@Override
	public void insertOrReplace(List<ScanRuleInfo> datas) {

		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
			try {
				db.beginTransaction();
				for (ScanRuleInfo info : datas) {
					ContentValues values = buildContentValues(info);
					// res = db.insert(SCAN_RULE_TABLE, null, values);
					// if (res > 0) {
					// Log.d("插入一条条码类型信息", "成功");
					// } else {
					if (replace(values)) {
						Log.d("插入一条条码类型信息", "成功");
					} else {
						Log.d("插入一条条码类型信息", "失败");
						// }
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("insertList", e.getMessage());
			} finally {
				datas.clear();
				db.setTransactionSuccessful();
				db.endTransaction();
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
		}
	}

	public String getRegularByType(String type) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			StringBuilder regular = new StringBuilder();
			Cursor c = null;
			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.READ_DATABASE);
				c = db.rawQuery(REGULAR_BY_TYPE_SQL, new String[] { type });

				if (c != null) {
					while (c.moveToNext()) {
						String prefix = c.getString(c
								.getColumnIndex(ScanRuleConstant.PREFIX));
						String scanLength = c.getString(c
								.getColumnIndex(ScanRuleConstant.SCANLENGTH));
						String re = buildRegular(prefix, scanLength);
						if (re != null) {
							regular.append(re);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeCursor(c);
				closeDb(UnifiedStaticType.READ_DATABASE);
			}
			return regular.toString();

		}
	}

	public String getSpecificRegular() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			StringBuilder regular = new StringBuilder();
			Cursor c = null;
			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.READ_DATABASE);
				c = db.rawQuery(SPECIFIC_REGULAR_SQL, new String[] { "1" });

				if (c != null) {
					while (c.moveToNext()) {
						String prefix = c.getString(c
								.getColumnIndex(ScanRuleConstant.PREFIX));
						String scanLength = c.getString(c
								.getColumnIndex(ScanRuleConstant.SCANLENGTH));
						String re = buildRegular(prefix, scanLength);
						if (re != null) {
							regular.append(re);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeCursor(c);
				closeDb(UnifiedStaticType.READ_DATABASE);
			}
			return regular.toString();

		}
	}

	private String buildRegular(String startWith, String lenght) {
		if (startWith == null || startWith.length() == 0 || lenght == null
				|| lenght.length() == 0)
			return null;
		if (startWith.length() > Integer.parseInt(lenght))
			return null;
		return "^((" + startWith + ")[0-9]{"
				+ (Integer.parseInt(lenght) - startWith.length()) + "})$|";
	}

	@Override
	public void deleteAll() {

		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long res = -1;
			try {
				res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
						.delete(SCAN_RULE_TABLE, null, null);
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("deleteAll", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}

		}

	}
}
